/* A template for javascript
 * usage: first create an object of Template with your template string
 * the template pattern syntax is like this #{variable} or #{[0]}
 * it also support this syntax like #{obj.text}
 * Template.Evaluate take an argument of obj,if obj is a Object like {a:"a",b:"b"}
 * obj also could be an Array,this time the template become #{[0]}
 * for example:
 
 * var tpl = new Template('<a href="#{href}">#{text}</a>');
 * tpl.escapeHTML = true;
 * var obj = {href:"http://www.53wd.com",text:"我上我的，我的校园空间"};
 * tpl.Evaluate(obj)  //this return '<a href="http://www.53wd.com">我上我的，我的校园空间</a>'
 * 
 * OR:
 * var tpl = new Template('<a href="#{[0]}">#{[1]}</a>');
 * tpl.escapeHTML = true;
 * var arr = ["http://www.53wd.com","我上我的，我的校园空间"];
 * tpl.Evaluate(arr); //this also return '<a href="http://www.53wd.com">我上我的，我的校园空间</a>'
 * 
 * Author roamer  
 * EMAIL: roamer.roamer@gmail.com
 * Welcome to www.53wd.com
 */ 

var Template = function(templateText)
{
	this.text = templateText;
	this.escapeHTML = true;
	this.Evaluate = function(data)
	{
		var templateTxt = this.text;
		var obj = data;
		var a = new RegExp("#\\{[a-z_A-Z0-9$\\.\\[\\]]{1,}?\\}");
		var match = a.exec(templateTxt);
		var condition = true;
		do
		{	
			if(match==null)
			{				
				return templateTxt;
			}
			if(match.toString().length < 4) 
			{
				return templateTxt;
			}
			var variable = match.toString().slice(2,-1);
			var value = "";
			if(variable.indexOf("[") != -1 )
			{
				value = eval("obj" + variable).toString();
			}
			else
			{
				value = eval("obj." + variable).toString();
			}
			if(this.escapeHTML) value = value.escapeHTML();
			else{
				var node = document.createElement("div");
				node.appendChild(document.createTextNode(value));
				value = node.innerHTML;
			}
			templateTxt = templateTxt.replace(match.toString(),value);
			match = a.exec(templateTxt);
		}
		while(true)
		return templateTxt;
	}
}